<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

class OrdersController extends AppController {

    var $name = 'Orders';
    var $helpers = array(
        'Published'
    );
    var $components = array(
        'Session'
    );
    var $uses = array(
        'Order', 'District', 'transport_fee', 'Country'
    );
    var $transport_status = array(
        '0' => '--Trạng thái giao hàng--',
        '1' => 'Đang xử lý',
        '2' => 'Đang giao hàng',
        '3' => 'Đã giao hàng',
        '4' => 'Đã hủy'
    );
    var $payment_status = array(
        '0' => '--Trạng thái thanh toán--',
        '1' => 'Chưa thanh toán',
        '2' => 'Đã thanh toán',
    );

    var $transport_type = array(
        '0' => '--Kiểu vận chuyển--',
        '1' => 'Giao tận nơi',
        '2' => 'Nhận hàng tại hồng 3 lý',
        '3' => 'Ship hàng ngoại thành',
    );
    var $payment_type = array(
        '0' => '--Kiểu thanh toán--',
        '1' => 'Trả tiền mặt',
        '2' => 'Chuyển khoản',
        '3' => 'Trả tiền tại cửa hàng',
    );
    var $drawee = array(
        '1' => 'Người đặt hàng',
        '2' => 'Người nhận hàng'
    );
    var $product_type = array(
        '2' => 'Giỏ trái cây',
        '1' => 'Trái cây',
        '3' => 'Combo'
    );
    //build unit list
    var $sex_list = array(
        '1' => 'Nam',
        '0' => 'Nữ',
    );
    function index() {
        $request_params =   array_merge($this->params['named'], $this->params['form'], $this->data);
        $this->set('title_for_layout', Configure::read('site_name') . ' - Quản lý đơn đặt hàng');
        $page = array_key_exists('page', $request_params) ? $request_params['page'] : 1;
        $search = !empty($request_params['search']) ? $request_params['search'] : false;
        $date_start = !empty($request_params['filter_start_date']) ? $request_params['filter_start_date'] : false;
        $date_end = !empty($request_params['filter_end_date']) ? $request_params['filter_end_date'] : false;
        $order_status_filter = !empty($request_params['order_status']) ? $request_params['order_status'] : false;
        $order_payment_status_filter= !empty($request_params['payment_status']) ? $request_params['payment_status'] : false;
        $conditions = array();
        $conditions_sub = array();

        $preg = preg_match('@^H3L(.*)$@', $search, $match);
        //search
        if ($search) {
            if ($preg) {
                $id = intval($match[1]);
                $conditions['Order.id = ?'] = $id;
            }else{
                $conditions['OR']   =   array(
                    'Order.buyer_name LIKE ?' =>  "%$search%",
                    'Order.buyer_phone LIKE ?'    =>  "%$search%",
                    'Order.buyer_address LIKE ?'    =>  "%$search%",
                    'Order.buyer_email LIKE ?'    =>  "%$search%",
                    'Order.receiver_name LIKE ?'    =>  "%$search%",
                    'Order.receiver_phone LIKE ?'    =>  "%$search%",
                    'Order.receiver_address LIKE ?'    =>  "%$search%",
                    'Order.extra_content LIKE ?'    =>  "%$search%",
                );
            }
        }
        if ($order_payment_status_filter) {
            $conditions['Order.payment_status = ?'] = $order_payment_status_filter;
        }
        if ($order_status_filter) {
            $conditions['Order.transport_status = ?'] = $order_status_filter;
        }
        $this->set('filter_start_date', $date_start);
        $this->set('filter_end_date', $date_end);
        if($date_start){
            $pre = preg_match('@^([0-9]{1,2})-([0-9]{1,2})-([0-9]{1,4})$@', $date_start, $match);
            
            $date_start = "{$match[3]}-{$match[2]}-{$match[1]} 00:00:00";
            $conditions['Order.created >= ?'] = $date_start;
        }
        if($date_end){
            $pre = preg_match('@^([0-9]{1,2})-([0-9]{1,2})-([0-9]{1,4})$@', $date_end, $match);
            $date_end = "{$match[3]}-{$match[2]}-{$match[1]} 00:00:00";
            $conditions['Order.created <= ?'] = $date_end;
        }
        $this->paginate = array(
            'conditions' => $conditions,
            'limit' => Configure::read('limit_list'),
            'fields' => array("DATE_FORMAT(Order.created, '%W %d-%m-%Y %l:%i %p') AS `created`", 'id', 'total_price','payment_type','payment_status', 'transport_status'),
            'order' => array(
                'Order.id' => 'DESC'
            ),
        );
        $data = $this->paginate('Order');
        $this->set('order_status', $this->transport_status);
        $this->set('payment_status', $this->payment_status);
        $this->set('order_status_selected', $order_status_filter);
        $this->set('keyword', $search);
        $this->set('order_payment_status_selected', $order_payment_status_filter);
        $this->set('total', $this->params['paging']['Order']['count']);
        $this->set('data', $data);
        $this->set('limit_page', $this->paginate['limit']);
        $this->set('start_page', $page);
    }
    function remove() {
        $conditions = array(
            "{$this->Order->alias}.{$this->Order->primaryKey} IN (" . implode(',', $this->params['form']['cid']) . ')'
        );

        if ($this->Order->deleteAll($conditions)) {
            $this->Session->setFlash(sprintf("Xóa thành công %d Order", sizeof($this->params['form']['cid'])), 'msg', array(), 'msg');
        } else {
            $this->Session->setFlash('Không thể xóa', 'msg', array(), 'error');
        }
        $this->redirect(array('action' => 'index'));
    }

    function edit() {
        $params = array_merge($this->params['form'], $this->params['named']);
        if (isset($params['cid']) && is_array($params['cid'])) {
            $this->Order->id = $params['cid'][0];
        } else {
            $this->Order->id = array_key_exists('id', $params) ? $params['id'] : 0;
        }
        $this->set('title_for_layout', Configure::read('site_name') . ' - Chi tiết đơn hàng');
        if (empty($this->data)) {
            $fields = array(
                "*, DATE_FORMAT(buyer_birthday, '%d-%m-%Y') AS buyer_birthday,
                    DATE_FORMAT(time_send, '%d-%m-%Y %H:%m') AS time_send"
            );
            $this->data = $this->Order->read($fields);
        }
        $this->set('sex_list', $this->sex_list);
        $this->set('district_list', $this->District->getListAll());
        $this->set('product_type', $this->product_type);
        $this->set('payment_status', $this->payment_status);
        $this->set('payment_type', $this->payment_type);
        $this->set('transport_type', $this->transport_type);
        $this->set('drawee', $this->drawee);
        $this->set('transport_status', $this->transport_status);
        $this->set('data', $this->data);
    }

    function save() {
        $data = $this->data['Order'];
        $pre = preg_match('@^([0-9]{1,2})-([0-9]{1,2})-([0-9]{1,4})$@', $data['buyer_birthday'], $match);
        $data['buyer_birthday'] = "{$match[3]}-{$match[2]}-{$match[1]} 00:00:00";

        $pre = preg_match('@^([0-9]{1,2})-([0-9]{1,2})-([0-9]{1,4}) ([0-9]{1,2}):([0-9]{1,2})@', $data['time_send'], $match);
        $data['time_send'] = "{$match[3]}-{$match[2]}-{$match[1]} {$match[4]}:{$match[5]}:00";

        if (isset($data['id'])) {
            $data['user_modified'] = $this->Auth->user('id');
            $data['user_modified_ip'] = $_SERVER['REMOTE_ADDR'];
        } else {
            $data['user_created'] = $this->Auth->user('id');
            $data['user_created_ip'] = $_SERVER['REMOTE_ADDR'];
        }
        if($data['payment_status']==2){
            $data['checkout_time'] = date('Y-m-d H:i');
        }
        if(empty($data['receiver_district'])){
            $data['total_price_transport'] = null;
        }else{
            $data['total_price_transport'] = $this->transport_fee->cal_fee($data['receiver_district'], $data['total_price_order']);
        }
        $data['total_price']    =   $data['total_price_order'] + intval($data['total_price_transport']);
        if ($this->Order->save($data)) {
            $this->Session->setFlash('lưu thành công thông tin', 'msg', array(), 'msg');
        } else {
            $this->Session->setFlash($this->Order->invalidFields(), 'error', array(), 'msg');
        }
        $this->redirect(array('controller' => 'orders', 'action' => 'index'));
    }

    function cancel() {
        $this->redirect(array('controller' => 'orders', 'action' => 'index'));
    }

}

?>
